from pymongo import MongoClient
from matplotlib import pyplot as plt
from matplotlib import style
import time
import json
#从采集到的两个源json文件提取每个传感器每个动作的电压时间到json文件
config = {'tag_url':'E:/biyeshejiproject_all/tags_411.json',           #提取前的json标签文件
          'volt_url':'E:/biyeshejiproject_all/volts_411.json',         #提取后的json电压时间文件
          'draw_easy_time':'E:\PycharmProjects\project\static\json\easy_time.json',  #
          'draw_easy_volt':'E:\PycharmProjects\project\static\json\easy_volt.json',
          'action':'easy',
          'ndevices':3,
          }


'a simple example for drawing with .json file'

def draw_with_json(tag_url, volt_url,easy_time,easy_volt,action, ndevices=3):
    tagData = []
    device_S = set()
    action_S = set()
    try:
        f_tag = open(tag_url, 'r')
        f_volt = open(volt_url, 'r')

        lines_tag = f_tag.readlines()   #返回列表,包含所有行
        lines_volt = f_volt.readlines()

        #The amount of voltage data is quite big, store them with a generator
        # volt_generater = (line for line in lines_volt)

        for line in lines_tag:                        #依次读取每行
            #Turn the str to dict for the convinience of index after
            json_line = json.loads(line)              #json数据转成字典

            #For future to cancel the parameter 'action'
            action_S.add(json_line['tag'])             #把tag存进action的集合

            #List tagData store the whole data of the certain action
            if json_line['tag'] == action:
                tagData.append(json_line)              #把筛选动作的那一行存进列表，列表里面包含字典
        n=1;
        # for line in lines_volt:
        #     json_line = json.loads(line)
        #     #For future to cancel the parameter 'ndevices'
        #     device_S.add(json_line['device_no'])
        for data in tagData:
            initTime, termTime = data['inittime'], data["termtime"]
            print(initTime,termTime)

            times, volts = {}, {}                      #时间电压是字典，其中键值对中值就是列表，键就是设备号
            for i in range(1, ndevices + 1):
                times[i] = []
                volts[i] = []
            # I tried to use generator instead of list ,but I failed.
            # I don't know the exactly reason why generator can't work properly in a loop
            # for i in volt_generater:
            #     json_i = json.loads(i)
            #     if (json_i['time'] <= termTime) and (json_i['time'] >= initTime):
            #         device_no = int(json_i['device_no'])
            #         v = json_i['voltage']
            #         time = json_i['time']
            #         times[device_no].append(time)
            #         volts[device_no].append(v)

            for i in lines_volt:
                json_i = json.loads(i)
                device_S.add(json_i['device_no'])
                if (json_i['time'] <= termTime) and (json_i['time'] >= initTime):
                    device_no = int(json_i['device_no'])
                    v = json_i['voltage']
                    drawtime = json_i['time']
                    #st = time.localtime(drawtime)
                    #time_switch=time.strftime('%Y-%m-%d %H:%M:%S', st)
                    times[device_no].append(drawtime)
                    volts[device_no].append(v)

            if (n == 1):
                json_data = json.dumps(times)
                with open(easy_time, 'w') as f_six:
                    f_six.write(json_data)
                json_data = json.dumps(volts)
                with open(easy_volt, 'w') as f_six:
                    f_six.write(json_data)
    finally:
        if f_tag:
            f_tag.close()
        if f_volt:
            f_volt.close()


if __name__=='__main__':
    # First parameter:  the absolute path of tag.json
    # Second parameter: the absolute path of volt.json
    # Third parameter:  a certain action
    # 大动作：翻身(turn_over)、腿部伸展(legs_stretch)、手部伸展(hands_stretch)；
    # 小动作：腿部抽搐(legs_twitch)、手部抽搐(hands_twitch)、头部微小移动(head_move)；
    # 剧烈动作：抓握(grasp)、踢踹(kick)
    draw_with_json(tag_url=config['tag_url'],
                   volt_url=config['volt_url'],
                   easy_time=config['draw_easy_time'],
                   easy_volt=config['draw_easy_volt'],
                   action=config['action'],
                   ndevices=config['ndevices'])